<template>
  <div class="page-container">
    <div v-if="initLoad">
      <!-- 提示 -->
      <a-alert>
        <template v-if="carStewardStatus.isOpenCarHousekeep">
          1、开启车管家调度模式后，所有的长/短租订单由车管家针对交车、换车、还车负责人派单，相关负责人接单后，进行操作。
          <br />
          2、分配前，请确保分配的车管家有订单、工单、司机排班的权限，如未配置会影响车管家的操作。
        </template>
        <span v-else>关闭车管家调度模式后，无派单及接单相关功能，历史订单不受影响。</span>
      </a-alert>
      <!-- 开关 -->
      <div class="radio-wrap" v-if="carStewardStatus.editMode">
        <div class="title"> 车管家调度模式</div>
        <a-radio-group :default-value="carStewardStatus.isOpenCarHousekeep" @change="isOpenCarHousekeepChange">
          <a-radio :value="1">开启</a-radio>
          <a-radio :value="0">关闭</a-radio>
        </a-radio-group>
      </div>
      <div class="radio-wrap" v-else>
        <div class="title">
          车管家调度模式：{{ carStewardStatus.isOpenCarHousekeep ? '开启' : '关闭' }}
          <a-button
            size="mini"
            type="primary"
            @click="carStewardStatus.editMode = true"
            v-permission="'svms:business:work-order:car-steward.edit'"
            >编辑</a-button
          >
        </div>
      </div>
    </div>
    <a-skeleton v-else>
      <a-skeleton-line :rows="3" />
      <a-divider />
      <a-space size="large">
        <a-skeleton-shape size="large" />
        <a-skeleton-shape size="large" />
        <a-skeleton-shape size="large" />
      </a-space>
    </a-skeleton>

    <!-- 门店内容 -->
    <div class="store-content" v-show="carStewardStatus.isOpenCarHousekeep">
      <a-divider />

      <!-- 搜索栏 -->
      <div class="list-searcher-bar" v-if="carStewardStatus.editMode == false">
        <div class="form-search">
          <span class="title">门店</span>
          <remote-select v-model="carStewardStatus.siteId" type="multiple_site_listBystaff" />
        </div>
        <div class="form-operate-list">
          <a-button class="r-button" @click="resetFn">
            <template #icon><icon-refresh /></template>重置
          </a-button>
          <a-button class="search-button" type="primary" @click="searchFn">
            <template #icon><icon-search /></template>查询
          </a-button>
          <div style="flex: 1"></div>
          <a-button class="b-button" type="primary" @click="editFn" v-if="carStewardStatus.mode == 'view'"> 批量配置或编辑车管家 </a-button>
        </div>
      </div>
      <!-- 门店卡片 -->
      <a-spin :loading="loading" tip="加载中...">
        <a-scrollbar style="min-width: 60vw; width: calc(100% + 10px); height: 73vh; overflow-y: auto">
          <div class="card-list" v-if="carStewardStatus.isOpenCarHousekeep">
            <StoreCard
              style="width: calc(33.3% - 10px)"
              :index="index"
              v-for="(item, index) in carStewardStatus.storeList"
              :key="item.siteId"
              :item="item"
              @validateFn="validateFn"
              @addStoreListFn="addStoreListFn"
            />
          </div>
        </a-scrollbar>
      </a-spin>
      <a-empty v-if="loading == false && carStewardStatus.storeList.length == 0" description="没有门店" />
    </div>
  </div>

  <page-form-footer cancelText="返回" :cancelFn="cancelFn" :ok-loading="okLoading" @ok="submitFn" v-if="carStewardStatus.editMode" />
</template>

<script setup name="WorkOrderCarSteward">
  import { ref, onActivated, provide, reactive, nextTick, h } from 'vue'
  import StoreCard from './components/store-card.vue'
  import { getCarHousekeepDetail, updateCarHousekeep } from '@/api/business/workorder'
  import { Message } from '@arco-design/web-vue'
  import { Modal } from '@arco-design/web-vue'

  // 本页面的局部状态管理
  const carStewardStatus = reactive({
    isOpenCarHousekeep: false, // 是否开启车管家调度模式
    editMode: false, // 页面模式
    storeList: [],
    siteId: undefined,
    errSiteIdList: [], // 错误站点id列表
  })
  provide('carStewardStatus', carStewardStatus)

  // 编辑
  const editFn = () => {
    carStewardStatus.editMode = true
  }
  // 取消
  const cancelFn = () => {
    carStewardStatus.editMode = false
    getDetail()
  }

  // 搜索
  const searchFn = async () => {
    await getDetail()
    const querySite = carStewardStatus.siteId
    if (!querySite || querySite.length == 0) return
    carStewardStatus.storeList = carStewardStatus.storeList.filter((item) => {
      return querySite.includes(item.siteId + '')
    })
  }
  // 重置
  const resetFn = () => {
    carStewardStatus.siteId = undefined
    getDetail()
  }
  // 获取详情
  const loading = ref(false)
  const initLoad = ref(false)
  const getDetail = () => {
    return new Promise((resolve) => {
      loading.value = true
      getCarHousekeepDetail({})
        .then((res) => {
          if (res.code == 200) {
            carStewardStatus.storeList = res.result.list || []
            // 门店车管家最少保留1个
            carStewardStatus.storeList.forEach((item) => {
              item.carHousekeepList = item.list || []
              while (item.carHousekeepList.length < 1) {
                item.carHousekeepList.push({ staffId: undefined })
              }
            })
            carStewardStatus.isOpenCarHousekeep = res.result.isOpenCarHousekeep
          }
          resolve()
        })
        .finally(() => {
          nextTick(() => {
            loading.value = false
            initLoad.value = true
          })
        })
    })
  }

  // 校验
  const validateFn = () => {
    // 校验
    carStewardStatus.errSiteIdList = []
    carStewardStatus.storeList.forEach((store) => {
      let useable_count = 0
      store.carHousekeepList.forEach((item) => {
        if (item.staffId) {
          useable_count++
        }
        if (item.staffStatusName) {
          useable_count--
          if (item.staffStatusName == '选择重复，请重新选择') {
            useable_count = -99
          }
        }
      })
      if (useable_count <= 0) {
        carStewardStatus.errSiteIdList.push(store.siteId)
      }
    })
  }
  // 添加车管家
  const addStoreListFn = (index) => {
    carStewardStatus.storeList[index].carHousekeepList.push({ staffId: undefined })
  }
  // 保存
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    validateFn()
    // 开启再校验
    if (carStewardStatus.isOpenCarHousekeep && carStewardStatus.errSiteIdList.length > 0) {
      Message.warning('请检查门店配置')
      return
    }
    okLoading.value = true
    const listData = carStewardStatus.storeList.map((item) => {
      return {
        siteId: item.siteId,
        carHousekeepList: item.carHousekeepList.map((citem) => citem.staffId),
      }
    })
    const form = {
      list: listData,
      isOpenCarHousekeep: carStewardStatus.isOpenCarHousekeep,
    }
    updateCarHousekeep(form)
      .then((res) => {
        if (res.code == 200) {
          carStewardStatus.editMode = false
          noticeSuccess()
          searchFn()
        }
      })
      .finally(() => {
        okLoading.value = false
      })
  }

  // 增加开启后的提示
  const isOpenCarHousekeepChange = (val) => {
    if (val == 1) {
      Modal.info({
        title: '提示',
        width: '45vw',
        okText: '确认',
        content: () =>
          h('div', {}, [
            h('p', {}, '开启车管家对于订单及运营成本功能的影响如下：'),
            h('p', {}, '1、开启车管家后，订单的交车、还车、换车按钮将隐藏，需指派的工单负责人在工单中操作'),
            h('p', {}, '2、开启车管家后，未分配工单负责人时，订单的添加报销单、付款单按钮将隐藏，非工单负责人可在业务-运营成本中添加'),
          ]),
      })
      setTimeout(() => {
        carStewardStatus.isOpenCarHousekeep = val
      }, 200)
    } else {
      carStewardStatus.isOpenCarHousekeep = val
    }
  }

  // 获取数据，keep-alive详情状态刷新数据
  onActivated(() => {
    if (carStewardStatus.editMode == false) {
      getDetail()
    }
  })
</script>

<style lang="less" scoped>
  .store-content {
    .card-list {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      // gap: 16px;
    }
    .list-searcher-bar {
      display: flex;
      margin-bottom: 20px;
      .form-search {
        width: 254px;
        display: flex;
        margin-right: 20px;
        align-items: center;

        .title {
          flex-shrink: 0;
          font-size: 14px;
          color: #4e5969;
          line-height: 22px;
          margin-right: 24px;
        }
      }
      .form-operate-list {
        flex: 1;
        display: flex;
        .search-button {
          margin-left: 16px;
        }
      }
    }
  }
  .radio-wrap {
    margin-top: 10px;
    .title {
      margin-bottom: 12px;
      font-size: 14px;
      color: #1d2129;
      line-height: 22px;
    }
  }
  .close-wrap {
    margin: 20px 0;
  }
</style>
